/*
 *    Copyright (C) 2011-2012 Hai Bison
 *
 *    See the file LICENSE at the root directory of this project for copying
 *    permission.
 */

/*
 * PanelPreferencesNotification.java
 *
 * Created on Sep 16, 2011, 9:50:26 PM
 */
package group.pals.mailgate.preferences.ui;

import group.pals.mailgate.media.SoundPlayer;
import group.pals.mailgate.media.SoundPlayerAdapter;
import group.pals.mailgate.ui.IPreferences;
import group.pals.mailgate.preferences.Preferences;
import group.pals.utils.files.FileUtils;
import group.pals.utils.sys.MessageBox;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.commons.lang3.StringEscapeUtils;

/**
 *
 * @author Hai Bison
 */
public final class PanelPreferencesNotification extends javax.swing.JPanel implements IPreferences {

    private final Preferences _Preferences;
    private final SoundPlayer _SoundPlayer;

    /** Creates new form PanelPreferencesNotification */
    public PanelPreferencesNotification() {
        initComponents();

        this._Preferences = Preferences.getInstance();
        this._SoundPlayer = SoundPlayer.getNewInstance();
        initActions();
        initListeners();
    }

    private void initActions() {
        actionChooseFile = new ActionChooseFile();
        buttonChooseFile.setAction(actionChooseFile);
        actionTestSoundFile = new ActionTestSoundFile();
        actionTestSoundFile.setEnabled(false);
        buttonTestSoundFile.setAction(actionTestSoundFile);
    }

    public void initListeners() {
        _SoundPlayer.addSoundPlayerListener(new SoundPlayerAdapter() {

            @Override
            public void soundPlay(SoundPlayer sender) {
                actionTestSoundFile.rename("Stop");
            }

            @Override
            public void soundStop(SoundPlayer sender) {
                actionTestSoundFile.rename(ActionTestSoundFile.DefaultName);
                actionTestSoundFile.setEnabled(true);
            }

            @Override
            public void soundRaised(SoundPlayer sender, Exception ex) {
                MessageBox.showErrMsg(null, null, String.format("Exception:\n\n%s", ex));
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        buttonChooseFile = new javax.swing.JButton();
        chkPlaySound = new javax.swing.JCheckBox();
        labelFilename = new javax.swing.JLabel();
        buttonTestSoundFile = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setLayout(new java.awt.GridBagLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setLayout(new java.awt.GridBagLayout());

        buttonChooseFile.setText("buttonChooseFile");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        jPanel1.add(buttonChooseFile, gridBagConstraints);

        chkPlaySound.setText("Play sound");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        jPanel1.add(chkPlaySound, gridBagConstraints);

        labelFilename.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        labelFilename.setBorder(javax.swing.BorderFactory.createTitledBorder("File:"));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        jPanel1.add(labelFilename, gridBagConstraints);

        buttonTestSoundFile.setText("buttonTestFile");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        jPanel1.add(buttonTestSoundFile, gridBagConstraints);

        jLabel1.setFont(new java.awt.Font("Dialog", 0, 12));
        jLabel1.setText("<html><p><b>Note:</b> Currently, the application only supports Ogg Vorbis audio format.</p></html>");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8);
        jPanel1.add(jLabel1, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        add(jPanel1, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonChooseFile;
    private javax.swing.JButton buttonTestSoundFile;
    private javax.swing.JCheckBox chkPlaySound;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel labelFilename;
    // End of variables declaration//GEN-END:variables

    /*----------------------------------------------------------------------------
     * IPreferences
     */
    public void loadPreferences() {
        chkPlaySound.setSelected(_Preferences.isPlaySoundOn());
        setSoundFile(_Preferences.getPlaySoundFile());
    }

    public boolean storePreferences(boolean prepare) {
        if (chkPlaySound.isSelected() && (getSoundFile() == null || !getSoundFile().isFile())) {
            MessageBox.showErrMsg(this, null, "Sound file does not exist");
            return false;
        }

        if (prepare) {
            return true;
        }

        _Preferences.setPlaySoundOn(chkPlaySound.isSelected());
        _Preferences.setPlaySoundFile(getSoundFile());

        return true;
    }

    public void closeResources() {
        if (_SoundPlayer.isPlaying()) {
            _SoundPlayer.stop();
        }
    }

    private void setSoundFile(File file) {
        if (_SoundPlayer.isPlaying()) {
            _SoundPlayer.stop();
        }

        this._SoundPlayer.setSoundFile(file);
        labelFilename.setText(file == null ? ""
                : String.format("<html><p align=\"center\" width=\"%d\">%s</p>",
                buttonChooseFile.getParent().getPreferredSize().width - buttonChooseFile.getPreferredSize().width - 10,
                StringEscapeUtils.escapeHtml4(file.getName())));
        actionTestSoundFile.setEnabled(file != null);
    }

    private File getSoundFile() {
        return this._SoundPlayer.getSoundFile();
    }

    /*----------------------------------------------------------------------------
     * ActionChooseFile
     */
    private ActionChooseFile actionChooseFile;

    private class ActionChooseFile extends AbstractAction {

        public ActionChooseFile() {
            super("Choose file...");
        }

        public void actionPerformed(ActionEvent e) {
            File[] files = FileUtils.dlgOpenFiles(null,
                    _Preferences.getLastWorkingDir().getAbsolutePath(), null, false,
                    JFileChooser.FILES_ONLY, true, false,
                    new Object[]{new FileNameExtensionFilter("Ogg Vorbis Audio Format", "ogg")});
            if (files != null) {
                //TODO: test if file is right ogg format
                setSoundFile(files[0]);
                _Preferences.setLastWorkingDir(files[0].getParentFile());
            }
        }
    }

    /*----------------------------------------------------------------------------
     * ActionTestSoundFile
     */
    private ActionTestSoundFile actionTestSoundFile;

    private class ActionTestSoundFile extends AbstractAction {

        public static final String DefaultName = "Test...";

        public ActionTestSoundFile() {
            super(DefaultName);
        }

        public void actionPerformed(ActionEvent e) {
            if (_SoundPlayer.isPlaying()) {
                setEnabled(false);
                _SoundPlayer.stop();
            } else {
                _SoundPlayer.play();
            }
        }

        /**
         * Renames this action.
         * @param name 
         */
        public void rename(String name) {
            putValue(NAME, name);
        }
    }
}
